import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { getUserInfoApi } from "@/api/auth";
// 创建异步action
export const getUserInfo = createAsyncThunk("user/getUserInfo", async () => {
  const res = await getUserInfoApi();
  return res.result;
  // console.log("params",res,token);
});

const authSlice = createSlice({
  name: "user",
  initialState: {
    userInfo: JSON.parse(localStorage.getItem("userInfo")) || {},
  },
  reducers: {
    setLogOut(state, action) {
      state.userInfo = {};
      localStorage.removeItem("token");
      localStorage.removeItem("userInfo");
    },
  },
  extraReducers(builder) {
    builder
      .addCase(getUserInfo.pending, () => {
        console.log("进行中");
      })
      .addCase(getUserInfo.fulfilled, (state, { payload }) => {
        console.log("fulfilled", payload);
        state.userInfo = payload;
        localStorage.setItem("userInfo", JSON.stringify(payload));
      })

      .addCase(getUserInfo.rejected, (state, err) => {
        console.log("rejected", err);
      });
  },
});

const { setLogOut } = authSlice.actions;
export { setLogOut };

export default authSlice;
